<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <div class="content">
          <NSpace>
            <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="90"
              :model="formValue">
              <NFormItem label="类型:" path="type">
                <NSelect :options="typeList" clearable v-model:value="formValue.type" />
              </NFormItem>
              <div v-if="formValue.type == '文书'">
                <NSpace justify="space-between">
                  <NFormItem label="档号:" path="archiveNumber">
                    <NInput placeholder="请输入档号" class="commonWidth" :allow-input="stopNull"
                      v-model:value="formValue.archiveNumber" />
                  </NFormItem>
                  <NFormItem label="件号:" path="itemNumber">
                    <NInput placeholder="请输入件号" class="commonWidth" :allow-input="stopNull"
                      v-model:value="formValue.itemNumber" />
                  </NFormItem>
                </NSpace>
                <NSpace justify="space-between">
                  <NFormItem label="年度:" path="annualYear">
                    <NInput placeholder="请输入年度" class="commonWidth" v-model:value="formValue.annualYear"
                      :allow-input="onlyNumber" />
                  </NFormItem>
                  <NFormItem label="保管期限:" path="storagePeriod">
                    <NInput placeholder="请输入保管期限" class="commonWidth" :allow-input="stopNull"
                      v-model:value="formValue.storagePeriod" />
                  </NFormItem>
                </NSpace>
              </div>
              <div v-if="formValue.type == '非文书'">
                <NSpace justify="space-between">
                  <NFormItem label="项目号:" path="projectNumber">
                    <NInput placeholder="请输入项目号" class="commonWidth" :allow-input="stopNull"
                      v-model:value="formValue.projectNumber" />
                  </NFormItem>
                  <NFormItem label="分类号:" path="classificationNumber">
                    <NInput placeholder="请输入分类号" class="commonWidth" :allow-input="stopNull"
                      v-model:value="formValue.classificationNumber" />
                  </NFormItem>
                </NSpace>
                <NSpace justify="space-between">
                  <NFormItem label="目录号:" path="catalogNumber">
                    <NInput placeholder="请输入目录号" class="commonWidth" :allow-input="stopNull"
                      v-model:value="formValue.catalogNumber" />
                  </NFormItem>
                  <NFormItem label="案卷档号:" path="caseArchiveNumber">
                    <NInput placeholder="请输入案卷档号" class="commonWidth" :allow-input="stopNull"
                      v-model:value="formValue.caseArchiveNumber" />
                  </NFormItem>
                </NSpace>
                <NSpace justify="space-between">
                  <NFormItem label="案卷号:" path="caseNumber">
                    <NInput placeholder="请输入案卷号" class="commonWidth" :allow-input="stopNull"
                      v-model:value="formValue.caseNumber" />
                  </NFormItem>
                  <NFormItem label="顺序号:" path="orderNumber">
                    <NInput placeholder="请输入顺序号" class="commonWidth" :allow-input="stopNull"
                      v-model:value="formValue.orderNumber" />
                  </NFormItem>
                </NSpace>
                <NSpace justify="space-between">
                  <NFormItem label="卷内档号:" path="innerArchiveNumber">
                    <NInput placeholder="请输入卷内档号" style="width:850rem" :allow-input="stopNull"
                      v-model:value="formValue.innerArchiveNumber" />
                  </NFormItem>
                </NSpace>
              </div>
              <NSpace justify="space-between">
                <NFormItem label="文件编号:" path="fileNumber">
                  <NInput placeholder="请输入文件编号" class="commonWidth" v-model:value="formValue.fileNumber"
                    :allow-input="stopNull" />
                </NFormItem>
                <NFormItem label="文件题名:" path="fileTitle">
                  <NInput placeholder="请输入文件题名" class="commonWidth" v-model:value="formValue.fileTitle"
                    :allow-input="stopNull" />
                </NFormItem>
              </NSpace>
              <NSpace justify="space-between">
                <NFormItem label="责任者:" path="responsiblePerson">
                  <NInput placeholder="请输入责任者" :allow-input="stopNull" class="commonWidth"
                    v-model:value="formValue.responsiblePerson" />
                </NFormItem>
                <NFormItem label="文件日期:" path="fileDate">
                  <NDatePicker input-readonly placeholder="请选择文件日期" class="commonWidth" type="date"
                    v-model:formatted-value="formValue.fileDate" clearable />
                </NFormItem>
              </NSpace>
              <NSpace justify="space-between">
                <NFormItem label="页数:" path="pageCount">
                  <NInput placeholder="请输入页数" class="commonWidth" v-model:value="formValue.pageCount"
                    :allow-input="onlyNumber" />
                </NFormItem>
                <!-- <NFormItem label="密级:" path="securityLevel">
                  <NSelect :options="isSecretList" class="commonWidth" v-model:value="formValue.securityLevel" />
                </NFormItem> -->
              </NSpace>
              <NFormItem label="备注:" path="notes">
                <NInput v-model:value="formValue.notes" placeholder="请输入备注" clearable type="textarea"
                  style="width: 100%; min-height: 100rem" :allow-input="stopNull" />
              </NFormItem>
              <NFormItem label="附件:" path="fileId">
                <VUpload :file-list="fileList" @getList="handleUploadList" />
              </NFormItem>
            </NForm>
          </NSpace>
        </div>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NButton ghost @click="goBack">
        取消
      </NButton>
      <NButton type="primary" @click="confirm(false)" :loading="loading">
        保存
      </NButton>
    </NSpace>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againConfirm" title="保存提示">
      <div v-if="formValue.securityLevel == '非涉密'"
        style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要保存吗？
      </div>
      <div v-else>
        <NForm label-placement="left" label-width="80" size="small" style="min-width: 500px">
          <NFormItem>经办人承诺:</NFormItem>
          <NFormItem>1.本文件只限于上述用途，绝不做他用。</NFormItem>
          <NFormItem>
            2.本文件只限在办公室使用，并按保密文件存放，绝不再次复印，不携带外出。
          </NFormItem>
          <NFormItem>3.本文件如有遗失、泄密，本人自愿承担全部责任。</NFormItem>
        </NForm>
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  useMessage,
  NModal,
  NSelect,
  NDatePicker,
  type FormInst
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute } from 'vue-router'
import VUpload from '@/views/OA/Common/Upload.vue'
import type { FormRules } from 'naive-ui'

const route = useRoute()
const tags = useTagStore().tags
const message = useMessage()

const props = defineProps({
  title: { type: String, default: () => '档案录入' },
  id: { type: [Number, String], default: () => null },
  flag: { type: [Number, String], default: () => null }
})

//只能输入数字
const onlyNumber = (value: string) => {
  var regA = /^\d*\.{0,1}\d{0,2}$/
  return !value || regA.test(value)
}

//去除空格
const stopNull = (value: string) => {
  return !value.startsWith(' ') && !value.endsWith(' ')
}

const formValue = reactive<Record<string, any>>({
  type: null, //档案类型
  archiveNumber: null, //档号
  itemNumber: null, //件号
  annualYear: null, //年度
  storagePeriod: null, //保管期限

  projectNumber: null, //项目号
  classificationNumber: null, //分类号
  catalogNumber: null, //目录号
  caseArchiveNumber: null, //案卷档号
  caseNumber: null, //案卷号
  orderNumber: null, //顺序号

  innerArchiveNumber: null,  //卷内档号

  fileNumber: null, //文件编号
  fileTitle: null, //文件题名
  responsiblePerson: null, //责任者
  fileDate: null, //文件日期
  pageCount: null, //文件页数
  notes: null, //备注
  securityLevel: '非涉密', //密级
  fileId: null //附件
})

const rules: FormRules = {
  type: {
    required: true,
    message: '类型不能为空',
    trigger: ['change', 'blur']
  },
  archiveNumber: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入档号')
      if (value?.length > 100) return new Error('档号不得超过100字')
      return true
    }
  },
  itemNumber: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入件号')
      if (value?.length > 100) return new Error('件号不得超过100字')
      return true
    }
  },
  annualYear: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入年度')
      if (value?.length > 100) return new Error('年度不得超过100字')
      return true
    }
  },
  storagePeriod: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入保管期限')
      if (value?.length > 100) return new Error('保管期限不得超过100字')
      return true
    }
  },
  //非文书-S
  projectNumber: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入项目号')
      if (value?.length > 100) return new Error('项目号不得超过100字')
      return true
    }
  },
  classificationNumber: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入分类号')
      if (value?.length > 100) return new Error('分类号不得超过100字')
      return true
    }
  },
  catalogNumber: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入目录号')
      if (value?.length > 100) return new Error('目录号不得超过100字')
      return true
    }
  },
  caseArchiveNumber: {
    // required: true,
    // message: '保案卷档号不能为空',
    // trigger: ['input', 'blur']
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入案卷档号')
      if (value?.length > 100) return new Error('案卷档号不得超过100字')
      return true
    }
  },
  caseNumber: {
    // required: true,
    // message: '案卷号不能为空',
    // trigger: ['input', 'blur']
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入案卷号')
      if (value?.length > 100) return new Error('案卷号不得超过100字')
      return true
    }
  },
  innerArchiveNumber: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入卷内档号')
      if (value?.length > 100) return new Error('卷内档号不得超过100字')
      return true
    }
  },
  orderNumber: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入顺序号')
      if (value?.length > 100) return new Error('顺序号不得超过100字')
      return true
    }
  },
  //非文书-E
  fileNumber: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入文件编号')
      if (value?.length > 100) return new Error('文件编号不得超过100字')
      return true
    }
  },
  fileTitle: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入文件题名')
      if (value?.length > 100) return new Error('文件题名不得超过100字')
      return true
    }
  },
  responsiblePerson: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入责任者')
      if (value?.length > 100) return new Error('责任者不得超过100字')
      return true
    }
  },
  pageCount: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入页数')
      if (value > 9999) return new Error('页数不得超过9999')
      return true
    }
  },
  fileDate: {
    required: true,
    message: '文件日期不能为空',
    trigger: ['blur', 'change']
  },
  notes: {
    required: false,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (value?.length > 100) return new Error('备注不得超过100字')
      return true
    }
  },
}

const isSecretList = [
  {
    value: '涉密',
    label: '涉密'
  },
  {
    value: '非涉密',
    label: '非涉密'
  }
]

const typeList = [
  {
    value: '文书',
    label: '文书'
  },
  {
    value: '非文书',
    label: '非文书'
  }
]

//获取详情
const getInfo = async () => {
  const [error, res] = await sendRequest({
    module: 'file',
    api: 'maintenanceItem',
    uri: {
      id: props.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  fileList.value = res.data?.fileList
  Object.keys(formValue).map((it: any) => {
    // @ts-ignore
    formValue[it] = res.data[it]
  })
}

// 附件
const fileList = ref()
const handleUploadList = (v: any) => (formValue.fileId = v)

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}

// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const modalVisible = ref(false)
const contentContent = ref()
const confirm = (status: boolean) => {
  formValue.draft = status
  formRef.value?.validate(async (err) => {
    if (err) return
    contentContent.value = status ? '您确定要保存草稿吗？' : ' 您确定要保存吗？'
    modalVisible.value = true
  })
}

const againConfirm = async () => {
  if (props.id && !props.flag) {
    const [error, res] = await sendRequest({
      module: 'file',
      api: 'maintenanceUpdate',
      override: {
        data: {
          ...formValue,
          id: props?.id
        }
      }
    })
    modalVisible.value = false
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.msg)
    message.success(res.msg)
    goBack()
  } else {
    const [error, res] = await sendRequest({
      module: 'file',
      api: 'maintenanceSave',
      override: {
        data: formValue
      }
    })
    modalVisible.value = false
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.msg)
    message.success(res.msg)
    goBack()
  }
}

watch(
  () => formValue.isSecret,
  () => {
    if (formValue.isSecret == '涉密') {
      formValue.useTime = null
      formValue.backTime = null
    } else {
      formValue.sendUnit = null
      formValue.copies = null
    }
  }
)

watch(
  () => formValue.type,
  () => {
    if (formValue.type == '文书') {
      formValue.projectNumber = null
      formValue.classificationNumber = null
      formValue.catalogNumber = null
      formValue.caseArchiveNumber = null
      formValue.caseNumber = null
      formValue.orderNumber = null
    } else {
      formValue.archiveNumber = null
      formValue.itemNumber = null
      formValue.annualYear = null
      formValue.storagePeriod = null
    }
  }
)

// watch(
//   () => route,
//   () => {
//     if (route.path == '/OA/File/MaintenanceEdit' && props.title == '档案录入编辑' && props.id)
//       getInfo()
//   },
//   { deep: true, immediate: true }
// )
watch(
  () => props.id,
  () => {
    if (props.title == '档案录入编辑' && props.id) getInfo()
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.commonWidthA {
  width: 155rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 20rem 0 180rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        height: 130rem;
        background: #e1e1e1;
        padding: 15rem 20rem;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: auto;
          min-width: 150rem;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 0 10rem;
          margin-right: 20rem;
        }
      }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
